<?php

namespace app\api\controller;

use app\admin\model\Batch;
use app\admin\model\m\Apply;
use app\admin\model\m\Info;
use app\admin\model\pro\Birth;
use app\admin\model\pro\Breed;
use app\admin\model\pro\Daily;
use app\admin\model\pro\Disinfect;
use app\admin\model\pro\Ears;
use app\admin\model\pro\Group;
use app\admin\model\pro\Light;
use app\admin\model\pro\Milk;
use app\admin\model\pro\Milkout;
use app\admin\model\pro\Milkpre;
use app\admin\model\pro\Out;
use app\admin\model\pro\Select;
use app\admin\model\pro\Sex;
use app\admin\model\pro\Touch;
use app\admin\model\pro\Weight;
use app\common\controller\Api;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *  生 产
 */
class Produce extends Api
{
    /**
     * 前台提交过来,需要排除的字段数据
     */
    protected $excludeFields = [];      // demo: ['info_data','group_id'];
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (array_key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else if (array_key_exists($this->excludeFields, $params)) {
            unset($params[$this->excludeFields]);
        }
        return $params;
    }

//    public function demo(){
//        echo '管理员id是: ' . $this->auth->id ;
//        echo '生产管理初始化';
//    }

    // 测试调拨1:   曾祖代厂-后备兔库(x厂)  转    在产种兔库(选择厂)
    public function test_diaobo1($zhongtu_num = 0, $out = [], $in = [] ){
        //$zhongtu_num = 500 ;
        //$factory_id = 1 ;
        //$factory_in_store = 1 ;

        // 1  曾祖代厂-后备兔库   调出
        // 查   曾祖代厂-后备兔库(x厂)   的库信息;   一般一个归属库= 一个创建的库
        $storem1 = Db::name("storem1")
            ->where("factory_id", $out['factory_id'] )
            ->where("storea_id", $out['storea_id'] )
            ->order("id DESC")
            ->find();

        $storem1_in = Db::name("storem1")
            ->where("factory_id", $in['factory_id'])
            ->where("storea_id", $in['storea_id'] )
            ->order("id DESC")
            ->find();

        $data_out = [
            'factory_id' => $storem1['factory_id'],
            'storesub_id' => $storem1['storesub_id'],
            'store1_id' => $storem1['store1_id'],
            'storea_id' => $storem1['storea_id'],
            'storem1_id' => $storem1['id'],
            'group_id'=> $out['group_id'],
            'batch_id'=> $out['batch_id'],
            'cal' => '出库',
            'num' => $zhongtu_num,
            'cal_num' => -$zhongtu_num,
            'field1' => '生产调拨',
            'field2' => $out['pinxi_id'] ? $out['pinxi_id']: 0,
            'status' => 'normal',
            'createtime' => time()
        ];

        //  2  本厂-在产种兔库   调入
        $data_in = [
            'factory_id' => $storem1_in['factory_id'],
            'storesub_id' => $storem1_in['storesub_id'],
            'store1_id' => $storem1_in['store1_id'],
            'storea_id' => $storem1_in['storea_id'],
            'storem1_id' => $storem1_in['id'],
            'group_id'=> $in['group_id'],
            'batch_id'=> $in['batch_id'],
            'cal' => '入库',
            'num' => $zhongtu_num,
            'cal_num' => $zhongtu_num,
            'field1' => '生产调拨',
            'field2' => $in['pinxi_id'] ? $in['pinxi_id']: 0,
            'status' => 'normal',
            'createtime' => time()
        ];

        $re['out'] = Db::name("storepro")->insert($data_out);
        $re['in'] = Db::name("storepro")->insert($data_in);

        return $re;
    }

    // 加光
    // 加光数为记录数据更新种免数为结点数据，即为从后备自用库中调拨至祖代在产种兔库下该生产组的种免数量
    // 后备自用库-> 祖代在产种兔库
    public function light(){
        $data = $this->request->post();
        $this->model = new Light();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过";  //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        if (empty($params['newdate'])) { $this->error('加光日期未找到,请联系管理员'); }
        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $batch = Db::name("batch")->where("id", $params['batch_id'])->find();
//        echo Db::getLastSql();die;
//        print_r($batch) ;die;
//        print_r($params) ;die;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            $my_store = Db::name("storem1")->where("factory_id", $factory_id )->where("storea_id", 1)->order("id DESC")->find();

//            DEMO
//            [zhongtu] => Array
//            (
//                [0] => Array
//                (
//                    [batch_id] => 43
//                    [num] => 100
//                    [data] => Array
//                          (
//                             [storea_id] => 5
//                            [factory_id] => 3
//                            [group_id] => 30
//                            [batch_id] => 43
//                            [name] => 种兔1组1批
//                            [pinxi_id] => 5
//                            [stock_num] => 9900
//                            [text] => 种兔1组1批 ( 祖代-D )  库存: 9900
//                            [value] => 43
//                        )
//                )

            // #demo
            # 出库数据:     zhongtu为多选, 分别: 批次+品系+数量
            $trans_total = 0;
            $num_total = 0;
            // $num_total = $num_total + $params['num'] ;
            $log_from = [];
            foreach( $params['zhongtu'] as &$val){
                if( intval($val['num']) < 1 ){ continue; }
                //$out_store = Db::name("storepro a")->where("a.factory_id", 3)->order("a.id DESC")->find();
                $val['num'] = intval($val['num']);
                $outf = [
                    'factory_id'=> $val['data']['factory_id'] ,       //  #曾祖代厂-后备兔库  >   在产种兔库
                    'storea_id'=> $val['data']['storea_id'],
                    'group_id'=> $val['data']['group_id'],
                    'batch_id'=> "",    // $val['data']['batch_id'],
                    'field2'=> $val['data']['pinxi_id'],
                    'num' => $val['num'],
                    'cal_num' => -$val['num'],
                    'stock' => 0,   // $val['data']['stock_num']-$val['num'],       // #cfg  todo  stock 不能作为这条数据节点的库存, 也不能参与计算,和参考;
                    'price' => $val['data']['price'],           //  3.1 计算成本???
                    'total' => my_mult($val['data']['price'], $val['num'], "2") ,
                    'cal_total' => my_mult($val['data']['price'], -$val['num'], "2") ,
                    'cal' => "生产出库",
                    'field1'=> "种兔生产出库",
                    'from_factory_id'=> $val['data']['factory_id'],
                    'from_storea_id'=> $val['data']['storea_id'],
                    'to_factory_id'=> $factory_id,
                    'to_storea_id'=> 1,
                    'createtime' => time()
                ];
                $log[] = Db::name("storepro")->insert($outf);
                $num_total += $val['num'];
                $trans_total += $outf['total'];     // 调拨总金额
                $log_from = $outf ;
            }
            #自厂区出库数据
            if(0) {
                $my_group_pinxi_pro = Db::name("storepro")->where([
                    'factory_id' => $factory_id,
                    'group_id' => $params['group_id'],
                    'storea_id' => 1,
                    //'field2' => $params['batchData']['pinxi_id']
                ])->order("id DESC")->find();

                $out1 = [
                    'factory_id' => $factory_id,
                    'storea_id' => 1,            //  在产种兔库
                    'group_id' => $params['group_id'],
                    'batch_id' => "",
                    'field2' => $params['batchData']['pinxi_id'],
                    'num' => $params['num'],
                    'cal_num' => -$params['num'],
                    'stock' => 0,
                    //'price' => 0,                             //  3.1 计算成本??? 种兔成本未计入
                    'price' => $my_group_pinxi_pro['price'],             //    组别,品系,  获取自身组别的成本记录.
                    'total' => my_mult($my_group_pinxi_pro['price'], $params['num'], "2"),
                    'cal_total' => my_mult($my_group_pinxi_pro['price'], -$params['num'], "2"),
                    'cal' => "生产出库",
                    'field1' => "剩余母兔转出",
                    'from_factory_id' => $factory_id,
                    'from_storea_id' => 1,
                    'to_factory_id' => $factory_id,
                    'to_storea_id' => 1,
                    'createtime' => time()
                ];
                $addout = Db::name("storepro")->insert($out1);
            }
            #入库数据
            $inf = [
                'factory_id' => $factory_id ,
                'storea_id'=> 1,            //  在产种兔库
                'group_id'=> $params['group_id'],
                'batch_id'=> $params['batch_id'],
                'field2'=> $params['batchData']['pinxi_id'],
                'num' => $num_total,
                'cal_num' => $num_total,
                'stock' => 0,
                // 'price' => 0,               //  3.1 计算成本??? 种兔成本未计入
                'price' => 1 ,                  //  平均单价?  todo
                'total' => $num_total * 1 ,      //
                'cal_total' => $num_total * 1 ,
                'cal' => "生产入库",
                'field1' => "种兔生产入库",
                'from_factory_id'=> $log_from ? $log_from['factory_id'] : 0,
                'from_storea_id'=> $log_from? $log_from['storea_id'] : 0,
                'to_factory_id'=> $factory_id,
                'to_storea_id'=> 1,
                'createtime' => time()
            ];
            ####$addin = Db::name("storepro")->insert($inf);

            // 更新种兔数量
            ####$update['zhongtu_update'] = $num_total - $params['num'];
            $update['zhongtu_update'] = 0;

            $result = $this->model->allowField(true)->save($update);
//echo Db::getLastSql();
//print_r($out_store);die;
//die;

            if(!$my_store){
                Db::rollback();
                $this->error("本厂区未创建在产种兔库");
            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    // 配种
    public function breed    (){
        $data = $this->request->post();
        $this->model = new Breed();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;
        $params['rate'] = number_format( $params['rate'], 4) * 100 ;         //  todo  保留2位小数( 27% = 0.27 )   floor, number_format

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //print_r($params);die;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    // 摸胎
    public function touch    (){
        $data = $this->request->post();
        $this->model = new Touch();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = empty($params['newdate']) ? date("Y-m-d") :  $params['newdate'] ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    // todo  母兔转舍       3.2     隐藏阶段
    // 该阶段需填写数据为上批次断奶数断奶销售数断奶均重，系统自动计算断奶成活率、阶段料肉比阶段单只成本等
    public function turnout(){}

    // 接产
    //  数据:  产仔总数    //产活仔数    //产仔窝数窝均产仔数窝均产活子数产仔率
    // 产仔总数产活仔数产仔窝数为记录数据窝均产仔数窝均产活子数、产仔率为生产指标系统自动计算，产仔率-产仔窝数/配种数
    public function birth    (){
        $data = $this->request->post();
        $this->model = new Birth();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }


    // 数据: 选留总数 选留窝数 带仔率 选留公免数 选留母免数
    // *选留总数为结点数据即为在祖代仔兔库下该批次的初始数据在选留操作填报数据后以生产入库方式自动入库，批次号在系统内预设;选留窝数选留公免数、选留母兔数为记录数据，甜仔率为生产指标，带仔率-选留窝数/配种数
    // 选留 5日龄
    public function select   (){
        $data = $this->request->post();
        $this->model = new Select();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            // demo   选留:   #转入仔兔库
            $zitu_ = [
                'factory_id' => $this->auth->factory_id ,
                'storea_id'=> 2,                        //  生长兔
                'group_id'=> $params['group_id'],        //  3.1  生长兔批次, 可能不需要
                'batch_id'=> $params['batch_id'],
                'num' =>        $params['num'],         // 生长兔数量
                'cal_num' =>    $params['num'],
                'cal' =>    "生产入库",
                'field1' => "选留",
                'field2' => $params['batchData']['pinxi_id'],
                'stock' => 0,              //  =批次库存-
                'price' => 0,              //  todo  价格待定  /或
                                            //  todo  0320  计算成本?
                'createtime' => time()
            ];
            ####$zitu = Db::name("storepro")->insert($zitu_);


            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }


    public function milk     (){
        $data = $this->request->post();
        $this->model = new Milk();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }


    // 仔兔12日龄补奶操作不再进行，母兔群开始进行下个批次生产的加光操作

    // 仔兔19日龄母兔群开始进行下个批次配种操作

    // 26日龄 该阶段需填写数据为上批次出栏总数出栏种免数、断奶均重，系统自动计算断奶成活率、阶段料肉比、阶段单只成本等

    // 35日龄  断奶
    // 断奶总数、断奶销售数断奶均重为结点数据断奶成活率、断奶料肉比、断奶单只成本为生产指标，
    // 断奶成活率=断奶总/选留总数，
    // 断奶单只成本=断奶前物料成本/断奶总数断奶结点时,仔兔转变为生长兔，即:以断奶总数从仔兔库调拨至生长兔库
    //  ~祖代仔兔库-祖代生长兔库,  断奶总数-断奶销售数
    public function milkout  (){
        $data = $this->request->post();
        $this->model = new Milkout();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;
        $params['truedate'] = date("Y-m-d");   //is_numeric($params['truedate']) ? date("Y-m-d H:i:s", $params['truedate']/1000): $params['truedate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            // demo     #仔兔库        >   孤树厂-生长兔库
            $inf = [
                'factory_id' => $this->auth->factory_id ,
                'storea_id'=> 2,            //  仔兔转出,生长兔库转入
                'group_id'=> $params['group_id'],        //
                'batch_id'=> $params['batch_id'],
                'num' =>        $params['num'],
                'cal_num' =>    -$params['num'],
                'cal' => "生产出库",
                'field1' => "断奶转出",
                'field2' => $params['batchData']['pinxi_id'],
                'stock' => 0,              //
                'price' => 0,              //  todo 3.1  断奶单只成本=断奶前物料成本/断奶总数断奶结点时,仔兔转变为生长兔，即:以断奶总数从仔兔库调拨至生长兔库
                // 出栏均重   特殊属性,计算成本用?
                'createtime' => time()
            ];
            ####$zitu = Db::name("storepro")->insert($inf);

            // todo 3.1 如果断奶选择了某厂的生长兔库,  则指定x厂x库
            $factory_to = isset($params['to_factory_id']) ? $params['to_factory_id'] : $inf['factory_id'] ;

            $shengzhang_  = $inf;
            $shengzhang_['storea_id'] = 3;
            $shengzhang_['factory_id'] = $factory_to;
            $shengzhang_['cal_num'] =  $inf['num'];
            $shengzhang_['cal'] = "生产入库";
            $shengzhang_['field1'] = "仔兔转到生长兔库";
           #### $shengzhang = Db::name("storepro")->insert($shengzhang_);




            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    // 分公母
    public function sex      (){
        $data = $this->request->post();
        $this->model = new Sex();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    // 断奶预防
    public function milkpre  (){
        $data = $this->request->post();
        $this->model = new Milkpre();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    public function ears     (){
        $data = $this->request->post();
        $this->model = new Ears();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    public function weight   (){
        $data = $this->request->post();
        $this->model = new Weight();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    // 生长兔49日龄下个批次开始产仔

    // 生长兔61日龄下下个批次开始加光

    // 生长兔68日龄下下个批次开始配种

    // 75日出栏
    // 出栏总数、出栏种兔数、出栏均重为结点数据，
    // ~~~ 出栏成活率、断奶料肉比, 断奶单只成本为生产指标，
    //~出栏成活率= (出栏总数-断奶销售)  / (断奶总数-断奶销售) ，
    //~批成活率=出栏成活率*断奶成活率，
    //~断奶料肉比=断奶至出栏总料耗/断奶至出栏总增重，
    //~批次单只成本=批次物料总成本/出栏总数，
    //~批次斤成本=批次单只成本/出栏均重 (斤)
    //出栏结点时，生长兔转变为后备兔， 即:曾祖代生产祖代过程以出栏种免数从曾祖代生长兔库调拨至后备自用库，
    //以出栏反系兔数(出栏总数-出栏种免数)调拨至待销售商品免库;
    //祖代生产父母代过程以出栏种免数从祖代生长兔库调拨至出栏待销售种兔库，
    //以出栏反系兔数调拨至待销售商品兔库
    public function out      (){
        $data = $this->request->post();
        $this->model = new Out();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        # 查询批次数据
        $filter['id'] = $params['batch_id'] ;
        $bd  = self::getBatche($filter);
//print_r($bd); die;
        // 计算出栏数据
        $params['a2']= 0;                                               //    断奶销售数
        $params['a3']= $bd['info']['pro_milkout'][0]['num'];           //    断奶总数
        $params['a1']= my_divide( ($params['num'] - $params['a2']), ($params['a3'] - $params['a2'] ) , 4 );           //    出栏成活率= (出栏总数-断奶销售)  / (断奶总数-断奶销售)

        $params['b1']= $params['a1'] * $bd['info']['pro_milkout'][0]['rate'] ;           //    批成活率=出栏成活率*断奶成活率
        $params['b2']= $bd['info']['pro_milkout'][0]['rate'];           //    断奶成活率

        $params['c2']= 200 ;                                            //    断奶至出栏总料耗          3.1 todo
        $params['c3']= 2 ;                                             //     断奶至出栏总增重          3.1 todo
        $params['c1']= my_divide($params['c2'], $params['c3'], 4 );//    断奶料肉比=断奶至出栏总料耗/断奶至出栏总增重

        $mate = self::getMateInfo($params['batch_id']);
//print_r($mate);die;
        $params['d2']= $mate ;                                            //    批次物料总成本           3.1 todo
        $params['d1']= my_divide($params['d2'], $params['num'], 4 );           //    批次单只成本=批次物料总成本/出栏总数，
        #$params['e2']= 0; //    批次单只成本
        $params['e1']= my_divide($params['d1'], $params['every'], 4 );           //    批次斤成本=批次单只成本/出栏均重 (斤)

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            // a. 出栏商品兔
            // demo
            $inf = [
                'factory_id' => $this->auth->factory_id ,
                'storea_id'=> 7,                        //  商品库
                'group_id'=> $params['group_id'],        //
                'batch_id'=> $params['batch_id'],
                'num' =>        $params['bnum'],
                'cal_num' =>    $params['bnum'],
                'cal' => "生产入库",
                'field1' => "商品兔入库",
                'field2' => $params['batchData']['pinxi_id'],
                'stock' => 0,             //
                'price' => 0,              //
                // 出栏均重   特殊属性,计算成本用?
                'createtime' => time()
            ];
            ####$shangpin = Db::name("storepro")->insert($inf);
            $inf_2 = [
                'factory_id' => $this->auth->factory_id ,
                'storea_id'=> 3,                        //  生长兔
                'group_id'=> $params['group_id'],        //
                'batch_id'=> $params['batch_id'],
                'num' =>        $params['bnum'],
                'cal_num' =>    -$params['bnum'],
                'cal' =>    "生产出库",
                'field1' => "生长兔出库",
                'field2' => $params['batchData']['pinxi_id'],
                'stock' => 0,             //
                'price' => 0,              //
                // 出栏均重   特殊属性,计算成本用?
                'createtime' => time()
            ];
            ####$shangpin_out = Db::name("storepro")->insert($inf_2);


            // demo     b. 出栏种兔数        #孤树厂-生长兔库    >  出栏兔库
            $zhongtu_ = [
                'factory_id' => $this->auth->factory_id ,
                'storea_id'=> 4,                        //   出栏兔库
                'group_id'=> $params['group_id'],        //
                'batch_id'=> $params['batch_id'],
                'num' =>        $params['nnum'],        // 出栏种兔数
                'cal_num' =>    $params['nnum'],
                'cal' =>    "生产入库",
                'field1' => "出栏种兔入库",
                'field2' => $params['batchData']['pinxi_id'],              //  查品系
                'stock' => 0,              //
                'price' => 0,              //
                // 出栏均重   特殊属性,计算成本用?
                'createtime' => time()
            ];
            ####$zhongtu = Db::name("storepro")->insert($zhongtu_);

            // demo      生长兔库转出
            $shengzhang_ =  $zhongtu_ ;
            $shengzhang_['storea_id'] = 3;           // 生长兔库
            $shengzhang_['num'] = $zhongtu_['num'];         //
            $shengzhang_['cal_num'] = -$zhongtu_['num'];    //
            $shengzhang_['cal'] = "生产出库";               //

            ####$shengzhang  = Db::name("storepro")->insert($shengzhang_);


            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }


    //   日报
    public function daily    (){
        //$data = $this->request->post();
        $this->model = new Daily();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $params['factory_id'] = $this->auth->factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            $this->success("提交成功");
            exit;
            #### 

            $a = [];    //统计log表插入的id

            //  todo    0309
            ####  die_child_num   仔兔出库
            if ($params['die_child_num'] > 0){
                $die = [
                    'factory_id' => $params['factory_id'],
                    'storea_id' => 2,
                    'group_id' => $params['group_id'],
                    'batch_id' => $params['batch_id'],
                    'num' => $params['die_child_num'],
                    'cal_num' => -$params['die_child_num'],
                    'cal' => "死亡出库",
                    'field1' => "",
                    'field2' => Batch::getPinxi($params['batch_id'])['pinxi_id'],
                    'stock' => 0,              //  批次库存-死亡数量
                    'price' => 0,              //  todo  价格待定
                    'createtime' => time()
                ];
                $a[] = Db::name("storepro")->insertGetId($die);
            }

            # 生长兔-淘汰     todo    成本
            if($params['set_new_num']>0) {
                $ss1 = [
                    'factory_id' => $params['factory_id'],
                    'storea_id' => 3,
                    'group_id' => $params['group_id'],
                    'batch_id' => $params['cb_batch_id'],
                    'num' => $params['set_new_num'],
                    'cal_num' => -$params['set_new_num'],
                    'cal' => "淘汰出库",
                    'field1' => "",
                    'field2' => Batch::getPinxi($params['cb_batch_id'])['pinxi_id'],
                    'stock' => 0,              //  批次库存-死亡数量
                    'price' => 0,              //  todo  价格待定
                    'createtime' => time()
                ];
                $a[] = Db::name("storepro")->insertGetId($ss1);
                $ss11 = $ss1;
                $ss11['storea_id'] = 6;
                $ss11['cal_num'] = $params['set_new_num'];
                $ss11['cal'] = "淘汰入库";
                $a[] = Db::name("storepro")->insertGetId($ss11);
            }
            # 生长兔-死亡
            if($params['die_new_num']>0) {
                $die11 = [
                    'factory_id' => $params['factory_id'],
                    'storea_id' => 3,
                    'group_id' => $params['group_id'],
                    'batch_id' => $params['cb_batch_id'],
                    'num' => $params['die_new_num'],
                    'cal_num' => -$params['die_new_num'],
                    'cal' => "死亡出库",
                    'field1' => "",
                    'field2' => Batch::getPinxi($params['cb_batch_id'])['pinxi_id'],
                    'stock' => 0,              //  批次库存-死亡数量
                    'price' => 0,              //  todo  价格待定
                    'createtime' => time()
                ];
                $a[] = Db::name("storepro")->insertGetId($die11);
            }

            # 在产种兔-淘汰   出库,  入库淘汰库
            if($params['set_zhong_num']>0) {
                $zaichan = [
                    'factory_id' => $params['factory_id'],
                    'storea_id' => 1,
                    'group_id' => $params['group_id'],
                    'batch_id' => $params['batch_id'],  // $params['cb_batch_id'],       //  计入批次1 ?
                    'num' => $params['set_zhong_num'],
                    'cal_num' => -$params['set_zhong_num'],
                    'cal' => "淘汰出库",
                    'field1' => "",
                    'field2' => Batch::getPinxi($params['cb_batch_id'])['pinxi_id'],
                    'stock' => 0,                   //  批次库存-死亡数量
                    'price' => 66.99,              //  todo  价格待定               0309    计算成本,写入:  计入到批次1的批次成本中的更新种兔更新成本下
                    'createtime' => time()
                ];
                $a[] = Db::name("storepro")->insertGetId($zaichan);
                $zaichan_add = $zaichan;
                $zaichan_add['storea_id'] = 6;
                $zaichan_add['cal_num'] = $params['set_zhong_num'];
                $zaichan_add['cal'] = "淘汰入库";
                $a[] = Db::name("storepro")->insertGetId($zaichan_add);
            }
            # 在产种兔-死亡   出库,  入库淘汰库
            if($params['die_zhong_num']>0) {
                $zaichand = [
                    'factory_id' => $params['factory_id'],
                    'storea_id' => 1,
                    'group_id' => $params['group_id'],
                    'batch_id' => $params['batch_id'],    // $params['cb_batch_id'],       //  计入批次1 ?
                    'num' => $params['die_zhong_num'],
                    'cal_num' => -$params['die_zhong_num'],
                    'cal' => "死亡出库",
                    'field1' => "",
                    'field2' => Batch::getPinxi($params['cb_batch_id'])['pinxi_id'],
                    'stock' => 0,                   //  批次库存-死亡数量
                    'price' => 66.11,              //  todo  价格待定
                    'createtime' => time()
                ];
                $a[] = Db::name("storepro")->insertGetId($zaichand);
            }

            # 淘汰后备种兔,   入库 淘汰库
            if( $params['set_pinxi_id'] > 0 && $params['set_pinxi_num'] > 0 ) {
                $bb = [
                    'factory_id' => $params['factory_id'],
                    'storea_id' => 5,
                    'group_id' => $params['group_id'],
                    'batch_id' => "",   //   $params['cb_batch_id'],    // todo 淘汰数不计入批次??
                    'num' => $params['set_pinxi_num'],
                    'cal_num' => -$params['set_pinxi_num'],
                    'cal' => "淘汰出库",
                    'field1' => "",
                    'field2' => $params['set_pinxi_id'],
                    'stock' => 0,              //  批次库存-死亡数量
                    'price' => 80.88,              //  todo  价格待定           #cfg 不计批次成本内, 但是xxxx
                    'createtime' => time()
                ];
                $a[] = Db::name("storepro")->insertGetId($bb);
                $bb_add = $bb;
                $bb_add['storea_id'] = 6;
                $bb_add['cal_num'] = $params['set_pinxi_num'];
                $bb_add['cal'] = "淘汰入库";
                $a[] = Db::name("storepro")->insertGetId($bb_add);
            }
            # 死亡后备兔
            if( $params['die_pinxi_id'] > 0 && $params['die_pinxi_num'] > 0 ) {
                $bbs = [
                    'factory_id' => $params['factory_id'],
                    'storea_id' => 5,
                    'group_id' => $params['group_id'],
                    'batch_id' => "",                   //   $params['cb_batch_id'],    // todo 淘汰数不计入批次??
                    'num' => $params['die_pinxi_num'],
                    'cal_num' => -$params['die_pinxi_num'],
                    'cal' => "死亡出库",
                    'field1' => "",
                    'field2' => $params['die_pinxi_id'],
                    'stock' => 0,              //  批次库存-死亡数量
                    'price' => 80.11,              //  todo  价格待定           #cfg 不计批次成本内, 但是xxxx
                    'createtime' => time()
                ];
                $a[] = Db::name("storepro")->insertGetId($bbs);
            }

            $checkid['checkid'] = implode(",", $a);
//            $this->model->where("id", $this->model->id )->data($checkid)->upda;
            $this->model->allowField(true)->save($checkid);
//print_r($a); die;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }
    public function disinfect(){
        $data = $this->request->post();
        $this->model = new Disinfect();

        if (false === $this->request->isPost()) { return ''; }
        $params = $this->request->post();
        if (empty($params)) { $this->error('不能提交空数据'); }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;  $params['status'] = "已通过"; //无需审核
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;
        $params['newdate'] = is_numeric($params['newdate']) ? date("Y-m-d H:i:s", $params['newdate']/1000): $params['newdate'] ;

        $factory_id = $this->auth->factory_id;
        $params['factory_id'] = $factory_id;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("提交成功");
    }

    // 计算批次的物料成本   其他领用单+领用单
    public static function getMateInfo($batch_id){
        $mate = Db::name("m_apply")
            ->where("batch_id", $batch_id )
            ->where("status", "已通过")
            ->where("deletetime", null )
            ->select();
        // TODO  3.1  物料申请如果软删除,需要同时修改状态为已驳回    #cfg
        //  TODO  3.1  物料的成本, 在领用时记录到申请表    #cfg

        $sum = 0;
        foreach ($mate as &$val){
            #$val['addup'] = $val['price'] * $val['num'] ;
            $sum +=  $val['price'] * $val['num'] ;
        }

        // 其他物料领用
        $mate_else = Db::name("m_applyes")
            ->where("batch_id", $batch_id )
            ->where("status", "已通过")
            ->where("deletetime", null )
            ->select();
        $sum_else = 0;
        foreach ($mate_else as &$vaa){
            $sum_else +=  $vaa['price'] * $vaa['num'] ;
        }

        return $sum+$sum_else;

//echo Db::getLastSql(); die;
//        print_r($mate); die;
    }

    // 查询列表
    public function lst_light(){
        $model = new Light();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_milk(){
        $model = new Milk();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_milkout(){
        $model = new Milkout();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_milkpre(){
        $model = new Milkpre();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_out(){
        $model = new Out();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_select(){
        $model = new Select();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_sex(){
        $model = new Sex();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_touch(){
        $model = new Touch();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_weight(){
        $model = new Weight();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_birth(){
        $model = new Birth();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_breed(){
        $model = new Breed();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    // TODO:  日报~
    public function lst_daily(){
        $model = new Daily();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_disinfect(){
        $model = new Disinfect();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }
    public function lst_ears(){
        $model = new Ears();
        $filter = $this->request->post();
        // 按筛选条件查询~
        $param = [];
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        if( $filter['group_id'] > 0 ){
            $param['a.group_id'] = $filter['group_id'];
        }
        if( $filter['batch_id'] > 0 ){
            $param['a.batch_id'] = $filter['batch_id'];
        }
        if( trim($filter['keyword']) != "" ){
            $param['b.name'] =  ['like', '%' . $filter['keyword'] . '%'];   // ['like', '%{$filter["keyword"]}%' ];
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        // TODO:
        $data['list'] = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->select();

        $this->success('成功', $data);
    }


    // 批次全部数据
    public function getBatch(){
        $filter = $this->request->get();
        if( !isset($filter['id']) || !$filter['id'] ){
            $this->success('无参数输入', '');
        }

        $res = self::getBatche($filter);
        $this->success('成功', $res);
    }

    //  该组别, 在产种兔库, 种兔数量
    public function getGroupZhongtu(){
        $filter = $this->request->get();
        if( !isset($filter['id']) || !$filter['id'] ){
            $this->success('无参数输入', '');
        }
        $factory_id = $this->auth->factory_id;

        $res = Db::name("storepro")
            ->field("*, sum(cal_num) as sum_num ")
            ->where("factory_id", $factory_id )
            ->where("group_id", $filter['id'] )
            ->where("storea_id", 1 )
            ->where("deletetime", null )
            ->select();
//echo Db::getLastSql();die;
        $this->success('成功', $res);
    }
    //  该组别批次 , 生长兔数量
    public function getBatchGrow(){
        $filter = $this->request->get();
        if( !isset($filter['id']) || !$filter['id'] ){
            $this->success('无参数输入', '');
        }

        $res = Db::name("storepro")
            ->field("factory_id,group_id,batch_id,storea_id, sum(cal_num) as sum_num ")
            ->where("batch_id", $filter['id'] )
            ->where("storea_id", 3 )
            ->where("deletetime", null )
            ->select();

        $this->success('成功', $res);
    }
    //  该组别, 在产种兔的数量总和
    public function getZhongqunZhongtu(){
        $filter = $this->request->get();
        if( !isset($filter['id']) || !$filter['id'] ){
            $this->success('无参数输入', '');
        }
        $res = Db::name("storepro")
            ->field("factory_id,group_id,batch_id,storea_id, sum(cal_num) as sum_num ")
            ->where("group_id", $filter['id'] )
            ->where("storea_id", 1 )
            ->where("deletetime", null )
            ->select();
        $this->success('成功', $res);
    }


    public static function getBatche($filter){

        $id = $filter['id'];
        // print_r($filter);

        // TODO   还需要:  日龄追踪;
        //  产仔日期起, 计算日龄
        //  ...
        $batch = Db::name("batch")->where("id", $id)->find();

        $line = [
            0 => [ 'key' => 'pro_light', 'name'=>'加光' ],
            1 => [ 'key' => 'pro_breed', 'name'=>'配种' ],
            2 => [ 'key' => 'pro_touch', 'name'=>'摸胎' ],
            3 => [ 'key' => 'pro_birth', 'name'=>'接产' ],
            4 => [ 'key' => 'pro_select', 'name'=>'选留' ],
            5 => [ 'key' => 'pro_milk',     'name'=>'补奶' ],
            6 => [ 'key' => 'pro_milkout', 'name'=>'断奶' ],
            7 => [ 'key' => 'pro_sex', 'name'=>'分公母' ],             // TODO:   流程顺序是否正确
            8 => [ 'key' => 'pro_milkpre', 'name'=>'断奶预防' ],
            9 => [ 'key' => 'pro_ears',     'name'=>'打耳号' ],
            10 => [ 'key' => 'pro_weight',   'name'=>'称重' ],
            11 => [ 'key' => 'pro_out',     'name'=>'出栏' ],
            12 => [ 'key' => 'pro_disinfect', 'name'=>'消毒冲舍' ],
        ];

        // 加光, 配种....
        $data['pro_light'] = Db::name("pro_light")->field("*, (num+zhongtu_update) as num ")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
//echo Db::getLastSql(); die;
        $data['pro_breed'] = Db::name("pro_breed")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
        $data['pro_touch'] = Db::name("pro_touch")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
        $data['pro_birth'] = Db::name("pro_birth")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();

        $data['pro_select'] = Db::name("pro_select")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
        $data['pro_milk'] = Db::name("pro_milk")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
        $data['pro_milkout'] = Db::name("pro_milkout")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
        $data['pro_sex'] = Db::name("pro_sex")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();              // 分公母
        $data['pro_milkpre'] = Db::name("pro_milkpre")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();

        $data['pro_ears'] = Db::name("pro_ears")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
        $data['pro_weight'] = Db::name("pro_weight")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
        $data['pro_out'] = Db::name("pro_out")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
        $data['pro_disinfect'] = Db::name("pro_disinfect")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();

        ## 日报
        $daily['pro_daily'] = Db::name("pro_daily")->where(['batch_id'=>$id, 'status'=>'已通过'])->order("id DESC")->select();
        //print_r($data); die;

        ## 日龄:  TODO:   接产是第一日, 是否需纠正天数?
        //  TODO   此处临时,  方法需要写到公共方法里,
        //  这里计算日龄, 从生产日开始到今天的日龄
        //  TODO   系统定时任务中, 也需要有个方法, 计算每个使用中的批次的日龄, 用以做预警提醒  (预警提前1-3天每天都要)   ***重要***
        $current = isset($data['pro_birth'][0]) ? floor( (time() - strtotime( $data['pro_birth'][0]['newdate'] ))/86400 ) : '';

        $res['batch'] = $batch;
        $res['info'] = $data;
        $res['line'] = $line;
        $res['daily'] = $daily;
        $res['age'] = $current ;     //日龄
        $res['calendar'] = Db::name("batchschedule")->where("batch_id", $id)->find() ;     //日龄

        return $res ;
        // $this->success('成功', $res);
    }

}

//  TODO   出栏成活率	出栏总数/（断奶总数-断奶出售）    未找到!




